package ink.metoo.auto.fishpi.shell

import com.google.gson.Gson
import com.google.gson.JsonObject
import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.Settings
import ink.metoo.auto.fishpi.call.ChatRoomCall
import ink.metoo.auto.fishpi.chatroom.Message
import ink.metoo.auto.fishpi.chatroom.RedPacket
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.io.path.Path

object DiggingRedEnvelopesMain : Runnable {

    private val gson = Gson()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    private var count = 0
    private var historyRedEnvelopeFile =
        Path("${System.getProperty("user.home")!!}/.auto-fishpi-active/history/${UUID.randomUUID()}.json").toFile()

    class HistoryRedEnvelopeData {
        val history = hashMapOf<String, Message>()
        var count: Int = 0

        fun push(message: Message) {
            ++ count
            history[message.oId!!] = message
        }
    }

    private val data = HistoryRedEnvelopeData()

    fun refreshData() {
        historyRedEnvelopeFile.parentFile.let {
            !it.exists() && it.mkdirs()
        }
        Log.debug("refreshData")
        historyRedEnvelopeFile.writeText(gson.toJson(data))
    }

    override fun run() {
        Log.info("history to $historyRedEnvelopeFile")
        val endDate = dateFormat.parse("2024-01-01 01:01:01")
        var lastMessage: Message? = null
        do {
            val messages: List<Message>
            if (lastMessage == null) {
                messages = ChatRoomCall.getMoreMessage(1, "md").data
                lastMessage = messages[messages.lastIndex]
                Log.info("on getMoreMessage")
            } else {
                val nextMessages =
                    ChatRoomCall.getContextMessage(oId = lastMessage.oId!!, mode = 1, size = 1000, type = "md").data
                if (nextMessages.size <= 1) {
                    return
                }
                messages = nextMessages.subList(1, nextMessages.lastIndex)
                lastMessage = messages[messages.lastIndex]
                count++
                Log.info("getContextMessage $count lastMessageID ${lastMessage.oId!!} ${lastMessage.time}")
                // sleep 30s
                TimeUnit.SECONDS.sleep(30L)
            }
            onMessages(messages)
        } while (lastMessage != null && endDate < dateFormat.parse(lastMessage.time))
        Log.info("the end. mitu2")
    }

    private fun onMessages(messages: List<Message>) = messages.forEach { message ->
        if (!message.isJsonContent) {
            return@forEach
        }
        val content = message.content
        val contentJson = gson.fromJson(content, JsonObject::class.java)
//        RootLog.debug("chatroom ${message.userName} json message: $content")
        if (contentJson.get("msgType").asString != "redPacket") {
            return@forEach
        }
        doRedPacket(message, gson.fromJson(contentJson, RedPacket::class.java))
    }

    private fun doRedPacket(message: Message, redPacket: RedPacket) {
        if (redPacket.count <= redPacket.got) {
            // 红包已领完 无羊毛可拿
            return
        }
        // 是否我已领取
        val isMeReceived = redPacket.who.findLast { it.userName == Settings.fishpiClient.username } != null
        val isMeSend = message.isMe
        if (isMeSend) {
            data.push(message)
            refreshData()
            return
        }
        when (redPacket.type) {
            "heartbeat", "random", "average" -> {
                var i = 0
                if (!isMeReceived) {
                    ChatRoomCall.openRedPacket(message.oId!!)
                    i++
                }
                if (redPacket.count <= (redPacket.got + i)) {
                    data.push(message)
                    refreshData()
                }

            }

            "specify" -> {
                try {
                    val reciversStr = redPacket.recivers
                    val recivers = gson.fromJson(
                        reciversStr.replace("\\", ""),
                        Array<String>::class.java
                    )
                    var i = 0
                    if (recivers.contains(Settings.fishpiClient.username)) {
                        if (!isMeReceived) {
                            ChatRoomCall.openRedPacket(message.oId!!)
                            i++
                        }
                    }
                    if (redPacket.count <= (redPacket.got + i)) {
                        data.push(message)
                        refreshData()
                    }
                } catch (e: Exception) {
                    Log.error(e.message, e)
                }

            }

            "rockPaperScissors" -> {
                data.push(message)
                refreshData()
            }
        }
    }


}

fun main() {
    DiggingRedEnvelopesMain.run()
}